package com.zyj.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockTest1 {
    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();
//        Condition condition = lock.newCondition();
        //第一个线程
        Thread thread1 = new Thread(() -> {
            try {
                System.out.println("Thread1 start");
                lock.lock();
                System.out.println("Thread1 lock1");
                //可重入锁, 只要已经获得锁了, 可以随便再获取锁, 但是别忘了用完之后, 也要对应的解锁
                lock.lock();
                System.out.println("Thread1 lock2");
                TimeUnit.SECONDS.sleep(5);
                lock.unlock();
                System.out.println("Thread1 unlock1");
                lock.unlock();
                System.out.println("Thread1 unlock2");
                System.out.println("Thread1 end");
            } catch (InterruptedException e) {
            }


        });
        thread1.start();
        //启动第二个线程前睡1秒
        TimeUnit.SECONDS.sleep(1);

        //第二个线程
        Thread thread2 = new Thread(() -> {
            try {
                System.out.println("Thread2 start");
                lock.lock();
                System.out.println("thread2 lock");
                TimeUnit.SECONDS.sleep(5);
                lock.unlock();
                System.out.println("thread2 unlock");
                System.out.println("Thread2 end");
            } catch (InterruptedException e) {
            }
        });
        thread2.start();

        //等两个线程执行完
        thread1.join();
        thread2.join();
    }
}
